package com.batchengine.worker;

import com.batchengine.pool.ExecutorWorkerPool;
import com.batchengine.pool.WorkerPool;
import static com.batchengine.schedular.CronSchedularWorkerManager.getCronSchedular;
import com.batchengine.task.TaskContext;
import static com.batchengine.worker.Status.FINISHED;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * User: sunil.incubator@yahoo.com
 * Date: Sep 14, 2009
 * Time: 9:36:24 PM
 */
public abstract class StopSignal extends TaskExecutor {

    private WorkerPool pool;

    public StopSignal(String name, long taskId, WorkerPool pool) {
        super(name, taskId);
        this.pool = pool;
    }


    public WorkerPool getPool() {
        return pool;
    }

    @Override
    protected void doWork(TaskContext context) {
        stopSignal(context);
    }

    /**
     * @param context
     */
    public abstract void stopSignal(TaskContext context);

    protected void removeWorkers(TaskContext context) {

        ScheduledTask scheduledTask = getCronSchedular().getScheduledTask(getJobId());
        if (null == scheduledTask) {
            return;
        }
        if (null == getPool()) {
            scheduledTask.setStatus(FINISHED);
            return;
        }

        WorkerPool workerPool = scheduledTask.getWorkerPool();
        if (null == workerPool || !(workerPool instanceof ExecutorWorkerPool)) {
            return;
        }

        removeWorkersFromPool(context);
    }

    protected void removeWorkersFromPool(TaskContext context) {

        ScheduledTask scheduledTask = getCronSchedular().getScheduledTask(getJobId());
        int count = -1;
        while (0 != count) {
            Map<String, Worker> map = getPool().getworkers();
            if (null != map && 0 < map.size()) {
                count = map.size();
                Set<String> workers = map.keySet();
                if (null == workers || 0 == workers.size()) {
                    continue;
                }
                for (Iterator<String> stringIterator = workers.iterator(); stringIterator.hasNext();) {
                    String name = stringIterator.next();
                    Worker worker = map.get(name);
                    if (Status.FINISHED.equals(worker.getStatus())) {
                        stringIterator.remove();
                    }
                }
            } else {
                count = 0;
            }
        }
        if (null != scheduledTask) {
            scheduledTask.setStatus(FINISHED);
        }
    }
}
